package cn.com.header.web.controller.common;

import cn.com.header.core.util.ApplicationUtils;
import cn.com.header.core.util.JSONResult;
import cn.com.header.web.model.sys.Authority;
import cn.com.header.web.model.sys.Role;
import cn.com.header.web.model.sys.User;
import cn.com.header.web.service.sys.AuthorityService;
import cn.com.header.web.service.sys.RoleService;
import cn.com.header.web.service.sys.UserService;
import cn.com.header.web.vo.sys.AuthorityVO;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;

@Controller
public class CommonController {
    private static final int MAX_AGE_LOGIN_NAME = 30 * 24 * 3600;
    @Resource
    private UserService userService;


    @Resource
    private AuthorityService authService;

    @Resource
    private RoleService roleSvc;


    /**
     * 生成验证码
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping("/randomCode")
    public void randomCode(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        //生成随机数
        String randomCode = UUID.randomUUID().toString().substring(0, 4);

        //把随机数放进Session中
        req.getSession().setAttribute("RANDOMCODE_IN_SESSION", randomCode);

        //创建图片对象
        int width = 70;
        int height = 40;
        int imageType = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(width, height, imageType);

        //画板
        Graphics g = image.getGraphics();
        g.setColor(Color.YELLOW);
        //绘制一个实心的矩形
        g.fillRect(1, 1, width - 2, height - 2);

        //把随机数画进图片中
        g.setColor(Color.BLACK);//设置随机数的颜色
        Font font = new Font("宋体", Font.BOLD + Font.ITALIC, 20);
        g.setFont(font);//设置随机数的字体和大小
        g.drawString(randomCode, 10, 28);
        //干扰线
        g.setColor(Color.GRAY);
        Random r = new Random();
        for (int i = 0; i < 100; i++) {
            g.fillRect(r.nextInt(width), r.nextInt(height), 2, 2);
        }

        //关闭
        g.dispose();
        //把图片对象以流的方式保存出去
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }


    /**
     * 用户登录
     *
     * @param user
     * @param result
     * @return
     */
    @RequestMapping(value = "login")
    @ResponseBody
    public String login(User user,String veryCodeLogin,Boolean rememberMe,BindingResult result, Model model, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {

        JSONObject obj=new JSONObject();
        try {
            Subject subject = SecurityUtils.getSubject();
            String sessionCode = JSONResult.getSessionCode();
            if (sessionCode == null){
                model.addAttribute("error", "验证码已过期！");
                obj.accumulate("resultVal",-2);
                return obj.toString();
            }
            if (!(veryCodeLogin.equals(sessionCode))){
                model.addAttribute("error", "验证码错误！");
                obj.accumulate("resultVal",-1);
                return obj.toString();
            }

            // 已登陆则 跳到首页
            if (subject.isAuthenticated()) {
                return "redirect:/";
            }
            if (result.hasErrors()) {
                model.addAttribute("error", "参数错误！");
                return "login";
            }

            // 身份验证
            user.setUserPwd(ApplicationUtils.sha256Hex(user.getUserPwd()));
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(),user.getUserPwd());
            final User authUserInfo = userService.selectByUsername(user.getUserName());

            subject.login(token);
            List<Authority> firstAuthList;
            if(subject.hasRole("admin")){
               firstAuthList=authService.getAllFirstAuth();
            }
            else{
                firstAuthList=authService.getFirstAuth(authUserInfo.getId());
            }

            List<AuthorityVO> authVOList=new ArrayList<AuthorityVO>();
            for(Authority auth:firstAuthList){
                AuthorityVO authVO=new AuthorityVO();
                BeanUtils.copyProperties(auth,authVO);
                List<Authority> childList=authService.getChildList(auth.getId());
                authVO.setChildren(childList);
                authVOList.add(authVO);
            }
            Role role=roleSvc.selectByUid(authUserInfo.getId());


            //session中存的东西
            request.getSession().setAttribute("authVOList",authVOList);
            request.getSession().setAttribute("userInfo", authUserInfo);
            request.getSession().setAttribute("title", "DCAMPUS走班排课");
            request.getSession().setAttribute("sessionRoleId", role.getId());
            // 是否设置记住账号rememberMe
            Cookie cookie = new Cookie("loginName",
                    rememberMe ? URLEncoder.encode(user.getUserName(), "utf-8") : null);
            cookie.setMaxAge(rememberMe ? MAX_AGE_LOGIN_NAME : 0);
            addCookie(cookie, request, response);
            obj.accumulate("resultVal",2);
        } catch (AuthenticationException e) {
            // 身份验证失败
            model.addAttribute("error", "用户名或密码错误 ！");
            obj.accumulate("resultVal",0);

        }
        return obj.toString();
    }    /**
     * 首页
     *
     * @param request
     * @return
     */
    @RequestMapping("index")
    public String index(HttpServletRequest request) {
        return "index";
    }

    /**
     * 用户登出
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        session.removeAttribute("userInfo");
        // 登出操作
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:page/login.do";
    }

    private void addCookie(Cookie cookie, HttpServletRequest request,
                           HttpServletResponse response) {
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);
    }

}